var currentPage = 1;
var pageSize = 20;
var totalPage = 1;

function load_items(items) {
  const listItems = document.getElementById('list-items');
  //clear listItems
  listItems.innerHTML = '';
  items.forEach(item => {
    const row = document.createElement('tr');
    row.innerHTML = "<td>" + item.id + "</td>" +
      "<td>" + item.name + "</td>" +
      "<td>" + item.age + "</td>" +
      "<td>" + item.gender + "</td>" +
      "<td>" + item.occupation + "</td>" +
      "<td>" + item.hobbies.join(',') + "</td>" +
      "<td><a href='./delete.do?id=" + item.id + "'>删除</a>&nbsp;" +
      "<a href='./edit.do?id=" + item.id + "'>修改</a></td>";
    listItems.appendChild(row);
  });
}

function update_pagination() {
  let pagination = document.getElementById('pagination-list');
  pagination.innerHTML = '';
  for (let i = 1; i <= totalPage; i++) {
    pagination.innerHTML += `
      <li><button class="pagination-link" aria-label="Goto page ${i}" onclick="load_page(${i})">${i}</button></li>
    `
  }
}

function load_page(page) {
  fetch('./list_by_page.do?page=' + page)
    .then(response => response.json())
    .then(data => {
      load_items(data.items);
      currentPage = data.pageNo;
      pageSize = data.pageSize;
      totalPage = data.count / pageSize;
      update_pagination();
    })
}

document.addEventListener('DOMContentLoaded', function () {
  load_page(currentPage);

  let nav = document.getElementById('pagination');
  nav.querySelector('.pagination-previous')
    .addEventListener('click', function () {
      load_page(currentPage - 1);
    });

  nav.querySelector('.pagination-next')
    .addEventListener('click', function () {
      load_page(currentPage + 1);
    });
});